package com.idanchuang.support.mybatis.crypt.resolver;

import com.idanchuang.support.mybatis.crypt.handler.CryptHandler;
import com.idanchuang.support.mybatis.crypt.handler.CryptHandlerFactory;
import org.apache.ibatis.binding.MapperMethod;

import java.util.List;
import java.util.Map;

/**
 * 有注解的方法加密处理者
 *
 * @author kamjin1996
 */
public class AnnotationMethodEncryptResolver implements MethodEncryptResolver {

    private List<MethodAnnotationEncryptParameter> methodAnnotationEncryptParameterList;

    public AnnotationMethodEncryptResolver() {
    }

    public AnnotationMethodEncryptResolver(List<MethodAnnotationEncryptParameter> methodAnnotationEncryptParameterList) {
        this.methodAnnotationEncryptParameterList = methodAnnotationEncryptParameterList;
    }

    @Override
    public Object processEncrypt(Object param) {
        Map map = (Map) param;
        Map newMap = new MapperMethod.ParamMap<>();
        newMap.putAll(map);
        for (MethodAnnotationEncryptParameter parameter : methodAnnotationEncryptParameterList) {
            String paramName = parameter.getParamName();
            if (map.containsKey(paramName)) {
                Object originObj = map.get(paramName);
                if (originObj == null) {
                    continue;
                }
                CryptHandler cryptHandler = CryptHandlerFactory.getCryptHandler(originObj, parameter.getCryptField());
                Object encryptObj = cryptHandler.encrypt(originObj, parameter.getCryptField());
                if (encryptObj == originObj) {
                    continue;
                }
                for (Object key : newMap.keySet()) {
                    if (originObj == newMap.get(key)) {
                        newMap.put(key, encryptObj);
                    }
                }
            }
        }

        return newMap;
    }

    public List<MethodAnnotationEncryptParameter> getMethodAnnotationEncryptParameterList() {
        return methodAnnotationEncryptParameterList;
    }

    public void setMethodAnnotationEncryptParameterList(List<MethodAnnotationEncryptParameter> methodAnnotationEncryptParameterList) {
        this.methodAnnotationEncryptParameterList = methodAnnotationEncryptParameterList;
    }
}
